package com.hcloud.audit.api.aspect;

import com.alibaba.fastjson.JSONObject;
import com.hcloud.audit.api.annontion.OperateLog;
import com.hcloud.audit.api.bean.OperateLogBean;
import com.hcloud.audit.api.event.OperateLogEvent;
import com.hcloud.audit.api.util.IPUtils;
import com.hcloud.auth.api.util.AuthUtil;
import com.hcloud.common.core.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Auther hepangui
 * @Date 2018/11/20
 */
@Aspect
@Slf4j
public class OperateLogAspect {
    @Around("@annotation(operateLog)")
    public Object around(ProceedingJoinPoint point, OperateLog operateLog) throws Throwable {

        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        saveLog(point, operateLog, time);
        return result;
    }

    private void saveLog(ProceedingJoinPoint point, OperateLog operateLog, long time) {
        String operate = operateLog.value();
        OperateLogBean bean = new OperateLogBean();
        //请求的参数
        Object[] args = point.getArgs();
        try {
            String params = JSONObject.toJSONString(args[0]);
            bean.setParams(params);
        } catch (Exception e) {

        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestURI = request.getRequestURI();
        bean.setUri(requestURI);
        //设置IP地址
        bean.setIp(IPUtils.getIpAddr(request));

        //用户名
        String username = AuthUtil.getUser().getName();
        bean.setUsername(username);
        bean.setOperate(operate);
        bean.setTime(time);
        bean.setCreateTime(new Date());
        //保存系统日志
        SpringUtil.publishEvent(new OperateLogEvent(bean));
    }
}
